package com.shanghaionstar.smart.presenter;

import android.text.TextUtils;

import com.midea.iot.sdk.cloud.openapi.MSmartSDK;
import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.framework.mvp.base.IMVPScheduler;
import com.onstar.cn.framework.mvp.base.IMVPView;
import com.onstar.cn.framework.mvp.base.core.BaseActivity;
import com.onstar.cn.framework.mvp.base.core.BasePresenter;
import com.onstar.cn.framework.network.entity.RequestEntity;
import com.onstar.cn.mag.LocalVehicleEntity;
import com.onstar.cn.smart.GetSmartDeviceResponse;
import com.onstar.cn.smart.SmartDevicesResponse;
import com.onstar.cn.smart.SmartTokenResponse;
import com.onstar.cn.smart.entity.ServiceItem;
import com.onstar.cn.weight.ToastView;
import com.shanghaionstar.R;
import com.shanghaionstar.enumtype.FunctionNameFindId;
import com.shanghaionstar.smart.SmartAddDeviceFrg;
import com.shanghaionstar.smart.SmartDeviceListFrg;
import com.shanghaionstar.smart.SmartHomeActivity;
import com.shanghaionstar.smart.SmartIntroduceFrg;
import com.shanghaionstar.smart.iview.ISmartEntranceView;
import com.shanghaionstar.smart.service.SmartHomeService;
import com.shanghaionstar.utils.ApplicationUtil;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.utils.NetConnectUtil;

import java.util.List;

import rx.functions.Action1;

/**
 * Created by 7828wc on 2016/6/22.
 */
public class SmartEntrancePresenter extends BasePresenter<Object> {
    private final static String SMART_SERVICE_OPENED="1";
    private final static String SMART_SERVICE_OPENING="2";
    private BaseActivity mContext;
    private ISmartEntranceView mSmartEntranceView;
    private SmartHomeService service;
    private static final String SMART_SERVICE = "SmartHome";
    private String optStatus = "-1";

    public SmartEntrancePresenter(IMVPScheduler mvpScheduler) {
        super(mvpScheduler);
    }

    @Override
    public void setView(IMVPView<Object> view) {
        super.setView(view);
        mSmartEntranceView = (ISmartEntranceView) view;
        mContext = (BaseActivity) mSmartEntranceView.onActivity();
        service = new SmartHomeService(mContext);
    }

    public void switchToDeviceList() {
        SmartDeviceListFrg deviceListFrg = new SmartDeviceListFrg();
        mContext.changeFragment(mContext.getSupportFragmentManager(), deviceListFrg, SmartDeviceListFrg.class, true);
    }

    /**
     * 根据是否存在设备列表显示相关fragment
     */
    public void checkDeviceList() {
        mSmartEntranceView.setLoading(true);
        subscription = service.getSmartDevices().subscribeOn(mvpScheduler.backgroundThread()).observeOn(mvpScheduler.mainThread())
                .subscribe(new Action1<SmartDevicesResponse>() {
                    @Override
                    public void call(SmartDevicesResponse mSmartDevicesRes) {
                        mSmartEntranceView.setLoading(false);
                        List<GetSmartDeviceResponse> mSmartDevices = mSmartDevicesRes.devices;
                        if (mSmartDevices != null && !mSmartDevices.isEmpty()) {
                            switchToDeviceList();
                        } else {
                            mSmartEntranceView.onReponseSuccess(null);
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {

//                        if (throwable != null)
//                            mSmartHomeView.onResponseError((OnStarException) throwable);
//                        switchToDeviceList();
                        mSmartEntranceView.onReponseSuccess(null);
                        mSmartEntranceView.setLoading(false);
                    }
                });
    }




    public void getServiceStatus() {
        mSmartEntranceView.setLoading(true);
        RequestEntity requestEntity = NetConnectUtil.getAuthRequestEntity(mContext);
        subscription = service.getServiceStatus(requestEntity, SMART_SERVICE).subscribeOn(mvpScheduler.backgroundThread()).observeOn(mvpScheduler.mainThread())
                .subscribe(new Action1<List<ServiceItem>>() {
                    @Override
                    public void call(List<ServiceItem> items) {
                        mSmartEntranceView.setLoading(false);
                        ServiceItem item = items.get(0);
                        if(item != null )
                            optStatus = item.optStatus;
                        if (item != null && item.optStatus.equalsIgnoreCase("1")) {
                            optStatus = item.optStatus;
                            return;
                        }
//                        if (item != null && item.optStatus.equalsIgnoreCase("2")) {
//                            optStatus = item.optStatus;
//                            mSmartEntranceView.showProtocolDia();
//                            return;
//                        }
                        mSmartEntranceView.showProtocolDia();
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        mSmartEntranceView.setLoading(false);
                        mSmartEntranceView.showProtocolDia();
                    }
                });
    }

    /**
     * 获取第三方token
     */
    public void getToken() {
        mSmartEntranceView.setLoading(true);
        RequestEntity entity = NetConnectUtil.getAuthRequestEntity(mContext);
        subscription = service.getToken(entity).subscribeOn(mvpScheduler.backgroundThread()).observeOn(mvpScheduler.mainThread())
                .subscribe(new Action1<SmartTokenResponse>() {
                    @Override
                    public void call(SmartTokenResponse response) {
                        mSmartEntranceView.setLoading(false);
                        String mAccessToken =  response.accessToken;
                        mAccessToken =  MSmartSDK.getInstance().getThirdManager().decodeAccessToken(mAccessToken);
                        ((SmartHomeActivity) mContext).mAccessToken = mAccessToken;
                        if (!TextUtils.isEmpty(mAccessToken)) {
                            checkDeviceList();
                        } else {
                            new ToastView(mContext).showToast(mContext.getString(R.string.smart_get_token_failed));
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        mSmartEntranceView.setLoading(false);
                        String errorMsg = throwable.getMessage();
                        new ToastView(mContext).showToast(errorMsg == null ?mContext.getString(R.string.smart_get_token_failed) : errorMsg);
                    }
                });
    }

//    /**
//     * @param thirdUid 根据第三方用户名获取token
//     */
//    public void getToken(String thirdUid) {
//        mSmartEntranceView.setLoading(true);
//        MSmartSDK.getInstance().getThirdManager().requestToken(thirdUid, new MSmartMapListener() {
//            @Override
//            public void onComplete(Map<String, Object> result) {
//                mSmartEntranceView.setLoading(false);
//                String mAccessToken = (String) result.get(Code.USER_ACCESS_TOKEN);
//                ((SmartHomeActivity) mContext).mAccessToken = mAccessToken;
//                if (!TextUtils.isEmpty(mAccessToken)) {
//                    goToAddDevice();
//                } else {
//                    new ToastView(mContext).showToast(mContext.getString(R.string.smart_get_token_failed));
//                }
//
//            }
//
//            @Override
//            public void onError(int errorCode, final String errorMsg) {
//                mSmartEntranceView.setLoading(false);
//                new ToastView(mContext).showToast(errorMsg == null ? "" : errorMsg);
//            }
//        });
//
//    }

    public void goToAddDevice() {
        SmartAddDeviceFrg addDeviceFrg = new SmartAddDeviceFrg();
        mContext.changeFragment(mContext.getSupportFragmentManager(), addDeviceFrg, SmartAddDeviceFrg.class, true);
    }

    public void goToFunIntro() {
        BusinessUtil.sendReportByClickType(mContext, FunctionNameFindId.Smarthome_introduction_tapin.getStringValue());
        SmartIntroduceFrg functionIntroFrg = new SmartIntroduceFrg();
        mContext.changeFragment(mContext.getSupportFragmentManager(), functionIntroFrg, SmartIntroduceFrg.class, true);
    }

    public void clickAdd() {
        BusinessUtil.sendReportByClickType(mContext, FunctionNameFindId.Smarthome_addappliance.getStringValue());
        if (TextUtils.isEmpty(((SmartHomeActivity) mContext).mAccessToken) || optStatus.equalsIgnoreCase("-1")) {
//            String ipdId = ApplicationUtil.getInstance().getIdpID();
            getToken();
        } else {
            goToAddDevice();
        }
    }

    /**
     * 同意协议
     */
    public void localVehicleService() {
        BusinessUtil.sendReportByClickType(mContext, FunctionNameFindId.Smarthomeagreement_agree.getStringValue());
        mSmartEntranceView.setLoading(true);
        LocalVehicleEntity entity = new LocalVehicleEntity();
        entity.setServiceName(SMART_SERVICE);
        entity.setVin(ApplicationUtil.getInstance().getVin());
        subscription = service.localVehicleService(entity).subscribeOn(mvpScheduler.backgroundThread()).observeOn(mvpScheduler.mainThread())
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String json) {
                        mSmartEntranceView.setLoading(false);
                        if (json != null && json.contains("E0000")) {
                            goToFunIntro();
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        mSmartEntranceView.setLoading(false);
                        if (mSmartEntranceView != null)
                            mSmartEntranceView.onResponseError((OnStarException) throwable);
                    }
                });
    }
}



